package com.security.manage.user.controller;

import com.security.manage.user.dto.ComboDto;
import com.security.manage.user.model.*;
import com.security.manage.user.repository.RoleRepository;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api("角色管理")
public class RoleController {

    @Resource
    private RoleRepository roleRepository;

    @PostMapping("/role")
    public ResData addRole(@RequestBody Role role, String permIds){

        Set<Permission> roles = new HashSet<>();
        if (StringUtils.isNotEmpty(permIds)) {
            for (String permId : permIds.split(",")) {
                roles.add(new Permission(Long.parseLong(permId)));
            }
        }
        role.setPermissions(roles);
        roleRepository.save(role);
        return new ResData(1,"成功");
    }

    @DeleteMapping("/role/{id}")
    public ResData delRole(@PathVariable("id") Long id){

        /*Optional<Role> role = roleRepository.findById(id);
        if (role.isPresent()){
            Set<User> users = role.get().getUsers();
            if (users!=null&&users.size()>0){
                return new ResData(0,"有用户关联了此角色，不能删除");
            }
        }else {
            return new ResData(0,"此角色不存在，不能删除");
        }*/
        roleRepository.deleteById(id);
        return new ResData(1,"成功");
    }

    @GetMapping("/role/{id}")
    public ResData getRole(@PathVariable("id") Long id){
        Optional<Role> role = roleRepository.findById(id);
        return role.map(dept -> new ResData<>(1, "获取成功", dept)).orElseGet(() -> new ResData(0, "获取失败"));
    }

    @GetMapping("role/combo")
    public ResData deptCombo(){
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Iterable<Role> all = roleRepository.findAll(sort);
        List<ComboDto> comboDtos = new ArrayList<>();
        all.forEach(dept -> comboDtos.add(new ComboDto(dept.getId(),dept.getRoleName())));
        return new ResData<>(1, "获取成功", comboDtos);
    }

    @GetMapping("/role/list")
    public ResData listRole(@RequestParam(value = "page",defaultValue = "0") Integer page,
                           @RequestParam(value = "size",defaultValue = "10") Integer size){

        Sort sort = Sort.by(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page, size, sort);
        Page<Role> pages = roleRepository.findAll(of);

        Map<String,Object> map = new HashMap<>();
        map.put("total",pages.getTotalElements());
        List<Role> collect = pages.get().collect(Collectors.toList());
        map.put("data",collect);

        return new ResData<>(1, "获取成功", map);
    }
}
